import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import md5 from 'js-md5'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  menus: [],
  mchId: '',
  mchName : '',
  employee:null
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_MCHID: (state, mchId) => {
    state.mchId = mchId
  },
  SET_MCHNAME: (state, mchName) => {
    state.mchName = mchName
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_EMPLOYEE: (state, employee) => {
    state.employee = employee
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, verifyCode, verifyCodeKey } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: md5(password), verifyCode: verifyCode, verifyCodeKey: verifyCodeKey }).then(response => {
        console.log(response)
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        console.log(error)
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    console.log(state.token)
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { userInfo, menus, employee } = data

        if (userInfo.avatar==null) {
          userInfo.avatar = "https://wpimg.wallstcn.com/69a1c46c-eb1c-4b46-8bd4-e9e686ef5251.png"
        }

        if (menus.length==0) {
          menus.push("admin");
        }

        // roles must be a non-empty array
        // if (!menus || menus.length <= 0) {
        //   reject('getInfo: roles must be a non-null array!')
        // }
        console.log(data)
        console.log('查看mch')
        commit('SET_EMPLOYEE', employee)
        commit('SET_MCHID', data.mchId)
        commit('SET_MCHNAME', data.mchName)
        commit('SET_MENUS', menus)
        commit('SET_NAME', userInfo.nickname)
        commit('SET_AVATAR', userInfo.avatar)
        commit('SET_INTRODUCTION', '')
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_MENUS', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_MENUS', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { menus } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', menus, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },
  sysMch({ commit }, data) {
    console.log(data)
    commit('SET_MCHID', data)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
